package cool.zhoujie;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextPaint;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.List;

import cool.zhoujie.adapter.TabFragmentAdapter;
import cool.zhoujie.db.DBUtil;
import cool.zhoujie.fragment.DailyRecFragment;
import cool.zhoujie.fragment.PlayFragment;
import cool.zhoujie.fragment.RecentPlayFragment;
import cool.zhoujie.service.PlayService;

public class MainActivity extends AppCompatActivity {

    private String[] mTitles = {"最近播放", "每日推荐", "榜单推荐"};

    private List<Fragment> fragmentList = new ArrayList<>();

    public PlayService.PlayBinder playBinder;

    private String TAG = Constant.TAG_SERVICE;

    public boolean isConnect = false;

    private TabLayout tabLayout;

    private ViewPager viewPager;

    private PlayService playService;

    private Intent serviceIntent;

    private ImageView toQuery;

    //处理服务连接回调
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "onServiceConnected: ");
            playBinder = (PlayService.PlayBinder) service;
            playService = playBinder.getService();
            isConnect = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        transparent();
        setContentView(R.layout.activity_main);
        bindViews();
        initViews();
        setListener();
        initData();
    }

    private void transparent() {
        if (Build.VERSION.SDK_INT >= 23) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
    }

    private void bindViews() {
        tabLayout = findViewById(R.id.tabLayout);
        viewPager = findViewById(R.id.viewPager);
        toQuery = findViewById(R.id.toQuery);
    }

    private void setListener() {
        tabLayout.addOnTabSelectedListener(new TabLayout.BaseOnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {

                int index = tab.getPosition();
                if (index == 0) {

                }

                TextView textView = new TextView(MainActivity.this);
                float selectedSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX
                        , 18, getResources().getDisplayMetrics());
                textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, selectedSize);
                textView.setText(tab.getText());
                textView.setTextColor(getResources().getColor(R.color.black));
                TextPaint paint = textView.getPaint();
                paint.setFakeBoldText(true);
                tab.setCustomView(textView);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                tab.setCustomView(null);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });

        toQuery.setOnClickListener(v -> {
            if (v.getId() == R.id.toQuery) {
                Intent intent = new Intent(MainActivity.this, QueryActivity.class);
                startActivity(intent);
            }
        });
    }

    private void initData() {
        //创建数据库
        DBUtil.initDB(this);
        Log.d(Constant.TAG_DB, "数据库成功创建");
        //启动服务
        serviceIntent = new Intent(MainActivity.this, PlayService.class);
        startService(serviceIntent);
        bindService(serviceIntent, connection, BIND_AUTO_CREATE);
        Log.d(Constant.TAG_SERVICE, "服务启动");
    }

    private void initViews() {
        //加载音乐播放碎片
        replaceFragment(new PlayFragment());
        for (int i = 0; i < mTitles.length; i++) {
            TabLayout.Tab tab = tabLayout.newTab();
            //三个页面写完之后，这里需要修改！！！
            tab.setTag(i);
            tab.setText(mTitles[i]);
            tabLayout.addTab(tab);
        }

        Fragment recentPlayFragment = new RecentPlayFragment();
        Fragment dailyRecFragment = new DailyRecFragment();
        Fragment dailyRecFragment2 = new DailyRecFragment();
        fragmentList.add(recentPlayFragment);
        fragmentList.add(dailyRecFragment);
        fragmentList.add(dailyRecFragment2);

        TabFragmentAdapter adapter = new TabFragmentAdapter(getSupportFragmentManager()
                , mTitles, fragmentList);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(0);

        tabLayout.setupWithViewPager(viewPager);

        //设置默认选中的tab字体
        TextView textView = new TextView(MainActivity.this);
        float selectedSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX
                , 18, getResources().getDisplayMetrics());
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, selectedSize);
        textView.setText(tabLayout.getTabAt(0).getText());
        textView.setTextColor(getResources().getColor(R.color.black));
        TextPaint paint = textView.getPaint();
        paint.setFakeBoldText(true);
        tabLayout.getTabAt(0).setCustomView(textView);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        playService.stopService(serviceIntent);
        playService.unbindService(connection);
        Log.d(Constant.TAG_SERVICE, "服务销毁");
    }

    private void replaceFragment(Fragment fragment) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.fragment_songPlay, fragment,"fragment_songPlay");
        transaction.commit();
    }

}
